<!--modified version of: https://docs.meilisearch.com/learn/tutorials/getting_started.html#integrate-with-your-project-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/templates/basic_search.css" />
</head>
<body>
<div class="wrapper">
  <div id="searchbox" focus></div>
  <div id="hits"></div>
  <div id="hits2"></div>

</div>
<script
    src="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/dist/instant-meilisearch.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meilisearch@latest/dist/bundles/meilisearch.umd.js"></script>
<script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4"></script>
<script>
    (async function () {
        const searchMessages = instantsearch({
            indexName: "threads",
            searchClient: instantMeiliSearch(
                "http://localhost:7700"
            )
        });

        const client = new MeiliSearch({host: "http://localhost:7700"});
        // put all users in a map so that we can display user names.
        const users = await client.getIndex("users")
            .then(usersResult => usersResult.getDocuments())
            .then(usersResult => usersResult.reduce((map, obj) => {
                map[obj.id] = obj.name;
                return map;
            }, {}));

        // put all channels in a map so that we can display channel names.
        const channels = await client.getIndex("channels")
            .then(usersResult => usersResult.getDocuments())
            .then(usersResult => usersResult.reduce((map, obj) => {
                map[obj.id] = obj.name;
                return map;
            }, {}));

        searchMessages.addWidgets([
            instantsearch.widgets.searchBox({
                container: "#searchbox"
            }),
            instantsearch.widgets.configure({hitsPerPage: 8}),
            instantsearch.widgets.hits({
                container: "#hits",
                templates: {
                    item(hit) {
                        return `
                      <div>
                      <div class="hit-name">
                          <b>${users[hit.user] || hit.user}</b>
                          (<i>${channels[hit.channel_id] || hit.channel_id}, ${instantsearch.highlight({
                            attribute: 'ts',
                            highlightedTagName: 'mark',
                            hit
                        })}</i>):
                          ${instantsearch.highlight({attribute: 'text', highlightedTagName: 'mark', hit})}
                      </div>
                      </div>
                  `
                    }
                }
            })
        ]);

        searchMessages.start()
    })();
</script>
</body>
</html>

